package core

import (
	"fmt"

	_ "github.com/go-sql-driver/mysql"
	"github.com/jmoiron/sqlx"
)

const (
	mysql         = "mysql"
	mysqlTemplate = "%s:%s@tcp(%s:%d)/%s?charset=%s&parseTime=True&loc=Local"
)

type MySQLParam struct {
	Host     string `json:"host" toml:"host"`
	Port     int    `json:"port" toml:"port"`
	User     string `json:"account" toml:"account"`
	Pwd      string `json:"pwd" toml:"pwd"`
	Charset  string `json:"charset" toml:"charset"`
	Database string `json:"database" toml:"database"`
}

// LinkMysql 连接数据库
func (my *MySQLParam) LinkMysql() (*sqlx.DB, error) {
	return sqlx.Open(mysql, my.getDataSourceName())
}

func (my *MySQLParam) getDataSourceName() string {
	return fmt.Sprintf(mysqlTemplate, my.User, my.Pwd, my.Host, my.Port, my.Database, my.Charset)
}
